﻿using System;
using System.Linq.Expressions;
using System.Web.Security;
using SBACN.WebSite.Code;
using SBACN.WebSite.Common;
using SBACN.WebSite.Models;

namespace SBACN.WebSite
{
	public partial class Forgetpwd : BasePage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			this.txt_valid.Attributes.Add("onkeyup","return DoLogin()");
			this.lblValid.Text = "";
			this.EMsg.Text = "";
		}

		protected void btn_Save_Click(object sender, EventArgs e)
		{
			if (this.txt_valid.Text.Trim().ToLower() != Session["Complain"].ToString().ToLower())
			{
				this.lblValid.Text = "验证码错误！";
				return;
			}
			string Name = this.Username.Text;
			string Email = this.Email.Text;

			Expression<Func<TB_User, bool>> f = (p => (p.UserName == Name && p.EMail == Email));
			var resultM = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_User>(f);

			if (resultM == null)
			{
				this.EMsg.Text = "用户名与邮箱不匹配！";
				return;
			}

			// 生成密码 发邮件 加密 数据库
			string NPassk = GeneratePassword(8);

			// 邮件内容
			Expression<Func<TB_SystemConfig, bool>> fff = (p => p.Type == "00090007" & p.Code == "6");
			var resultSystemConfig = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_SystemConfig>(fff);
			if (resultSystemConfig != null && resultSystemConfig.Status)
			{
				string conname = resultSystemConfig.Name.Replace("$Name", Name); ;
				string content = "";
				content = resultSystemConfig.Value.Replace("$Name", Name);
				content = content.Replace("$Password", NPassk);

				Mail.Instance.SendEMail(conname, content, Email);
			}

			string OMD5 = FormsAuthentication.HashPasswordForStoringInConfigFile(NPassk, "MD5").ToLower();
			string TMD5 = FormsAuthentication.HashPasswordForStoringInConfigFile(OMD5, "MD5").ToLower();

			resultM.Password = TMD5;
			DAL.DALHelper.Instance.Update<TB_User>(resultM);
			DAL.DALHelper.Instance.SaveChanges();

			ClientScript.RegisterClientScriptBlock(this.GetType(),"AlertMsg","<script> alert('邮件已发送，请查收邮件。');window.close(); </script>");
			//Response.End();
		}
	}
}